package com.yanqu.road.server.gameplayer.module.activity.share;

import com.yanqu.road.dao.impl.activity.share.ShareDataDaoImpl;
import com.yanqu.road.dao.impl.activity.share.ShareGoodsDaoImpl;
import com.yanqu.road.dao.impl.log.LogUserInfoDaoImpl;
import com.yanqu.road.entity.activity.ActivityInfo;
import com.yanqu.road.entity.activity.share.config.ShareConfig;
import com.yanqu.road.entity.enums.eGamePlayerEventType;
import com.yanqu.road.entity.enums.eLogMoneyType;
import com.yanqu.road.entity.enums.ePlayerAttrType;
import com.yanqu.road.entity.player.*;
import com.yanqu.road.logic.bussiness.activity.ShareActivityBusiness;
import com.yanqu.road.logic.config.GameConfig;
import com.yanqu.road.pb.activity.ShareProto;
import com.yanqu.road.server.GameServer;
import com.yanqu.road.server.gameplayer.GamePlayer;
import com.yanqu.road.server.gameplayer.module.base.GeneralModule;
import com.yanqu.road.server.gameplayer.module.patrons.PatronsModule;
import com.yanqu.road.server.gameplayer.module.player.AttributeModule;
import com.yanqu.road.server.gameplayer.module.player.BeautyModule;
import com.yanqu.road.server.gameplayer.module.player.CurrencyModule;
import com.yanqu.road.server.manger.activity.fouractivity.FourActivityMgr;
import com.yanqu.road.server.manger.activity.share.ShareActivityMgr;
import com.yanqu.road.server.manger.activity.share.ShareMgr;
import com.yanqu.road.server.manger.config.GoodsMgr;
import com.yanqu.road.server.protocol.ClientProtocol;
import com.yanqu.road.server.protocol.CrossProtocol;
import com.yanqu.road.server.protocol.GameErrorCode;
import com.yanqu.road.utils.date.DateHelper;
import com.yanqu.road.utils.property.Property;
import com.yanqu.road.utils.property.PropertyHelper;
import com.yanqu.road.utils.string.StringUtils;

import java.util.ArrayList;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class ShareModule extends GeneralModule {
    private UserShareData userShareData;
    private UserQyfxData userQyfxData;

    private void initUserShareData() {
        UserShareData tmpData = new UserShareData();
        tmpData.setUserId(getUserId());
        tmpData.setShareCode(ShareMgr.getShareCode(getUserId()));
        tmpData.setTodayShareTimes(0);
        tmpData.setNextShareTime(System.currentTimeMillis());
        tmpData.setLastResetTime(System.currentTimeMillis());
        tmpData.setInvitedServerId(0);
        tmpData.setInvitedUserId(0L);
        tmpData.setInvitedCode("");
        tmpData.setNextInvitationTime(System.currentTimeMillis());
        tmpData.setInsertOption();
        userShareData = tmpData;

        checkInvitedCode();
    }

    private Map<Integer, UserShareGoodsData> shareGoodsDataMap = new ConcurrentHashMap<>();

    public ShareModule(GamePlayer player) {
        super(player);
    }

    public void checkInvitedCode() {
        OpenInvitedData openInvitedData = ShareMgr.getOpenInvitedData(player.getUserInfo().getOpenId());
        if (openInvitedData != null && !StringUtils.isNullOrEmpty(openInvitedData.getInvitedCode())) {
            if (player.getUserInfo().getRegisterTime() + 3 >= openInvitedData.getRegisterTime()) {//加3秒容错
                String[] arr = openInvitedData.getInvitedCode().split("_");
                int serverId = Integer.parseInt(arr[0]);
                long userId = Long.parseLong(arr[1]);
                if (userId != getUserId()) {
                    // 有邀请码
                    userShareData.setInvitedServerId(serverId);
                    userShareData.setInvitedUserId(userId);
                    userShareData.setInvitedCode(openInvitedData.getInvitedCode());
                    return;
                }
            }
        }
        // 没有邀请码
        userShareData.setInvitedServerId(0);
        userShareData.setInvitedUserId(0L);
        userShareData.setInvitedCode("");
    }

    private boolean isNewUser() {
        Map<Long, Long> dataMap = new LogUserInfoDaoImpl().getUserServerListRegisterTime(player.getUserInfo().getOpenId());
        long originalServerId = player.getUserInfo().getOriginalServerId();
        for (Map.Entry<Long, Long> entry : dataMap.entrySet()) {
            long serverId = entry.getKey();
            long registerTime = entry.getValue() / 1000;
            if (originalServerId != serverId && player.getUserInfo().getRegisterTime() > registerTime) {
                return false;
            }
        }
        return true;
    }

    public int shareSuccess(boolean isFXYL) {
        ShareConfig config;
        if (isFXYL) {
            config = FourActivityMgr.getShareConfig();
        } else {
            config = ShareActivityMgr.getConfig();
        }
        if (config == null) {
            return GameErrorCode.E_ACTIVITY_NO_FOUND;
        }
        if (System.currentTimeMillis() < userShareData.getNextShareTime()) {
            return GameErrorCode.E_SHARE_CD;
        }
        int todayShareTimes = userShareData.getTodayShareTimes();
        if (todayShareTimes >= config.getShareDailyLimit()) {
            return GameErrorCode.E_SHARE_DAY_LIMIT;
        }
        ShareProto.ShareSuccessRespMsg.Builder resp = ShareProto.ShareSuccessRespMsg.newBuilder();
        resp.setRet(0);
        String shareReward = config.getShareReward();
        userShareData.setTodayShareTimes(todayShareTimes + 1);

        long nextZeroTime = DateHelper.getTodayZeroTimeStamp() + 24L * 3600 * 1000;
        if (nextZeroTime < System.currentTimeMillis() + config.getShareCD() * 1000 * 60L) {
            userShareData.setNextShareTime(nextZeroTime);
        } else {
            userShareData.setNextShareTime(System.currentTimeMillis() + config.getShareCD() * 1000 * 60L);
        }
        player.getModule(CurrencyModule.class).addCurrency(shareReward, eLogMoneyType.Share, eLogMoneyType.ShareReward);
        syncShareDataMsg();
        resp.setReward(shareReward);
        player.sendPacket(ClientProtocol.U_SHARE_SUCCESS_REWARD, resp);
        return 0;
    }

    public int invitationSuccess() {
        ShareConfig config = ShareActivityMgr.getConfig(); // 繁瑞说拿不是分享有礼的配置
        if (config == null) {
            return GameErrorCode.E_ACTIVITY_NO_FOUND;
        }

        if (System.currentTimeMillis() < userShareData.getNextInvitationTime()) {
            return GameErrorCode.E_INVITATION_CD;
        }

        long nextZeroTime = DateHelper.getTodayZeroTimeStamp() + 24L * 3600 * 1000;
        if (nextZeroTime < System.currentTimeMillis() + config.getInvitationCD() * 1000 * 60L) {
            userShareData.setNextInvitationTime(nextZeroTime);
        } else {
            userShareData.setNextInvitationTime(System.currentTimeMillis() + config.getInvitationCD() * 1000 * 60L);
        }
        syncShareDataMsg();

        return 0;
    }

    @Override
    public void loginSendMsg() {
        if (userShareData == null) {
            initUserShareData();
        }
        try {
            player.notifyListener(eGamePlayerEventType.ShareNum.getValue());
            player.notifyListener(eGamePlayerEventType.ShareEarnSpeed.getValue());
            player.notifyListener(eGamePlayerEventType.ShareRecharge.getValue());
        } catch (Exception e) {

        }
        syncShareDataMsg();
        ActivityInfo activityInfo = ShareActivityMgr.getQyfxActivityInfo();
        if (activityInfo != null) {
            initUserData(activityInfo.getActivityId());
            syncUserData();
        }
    }

    public void syncShareDataMsg() {
        ShareConfig config = ShareActivityMgr.getConfig();
        if (config == null) {
            config = FourActivityMgr.getShareConfig();
            if (config == null) {
                return;
            }
        }
        ShareProto.ShareDataMsg.Builder msg = ShareProto.ShareDataMsg.newBuilder();
        msg.setInvitationCode(ShareMgr.getShareCode(getUserId()));
        msg.setNextShareTime(DateHelper.toSecond(userShareData.getNextShareTime()));
        int num = ShareMgr.getInviteNum(getUserId(), System.currentTimeMillis() / 1000);
        msg.setTodayInvitationLeftTimes(num);
        msg.setTodayShareLeftTimes(config.getShareDailyLimit() - userShareData.getTodayShareTimes());
        msg.setNextInvitationTime(DateHelper.toSecond(userShareData.getNextInvitationTime()));
        player.sendPacket(ClientProtocol.U_SHARE_SYNC_MSG, msg);
    }

    @Override
    public boolean loadData() {
        userShareData = new ShareDataDaoImpl().getUserShareData(getUserId());
        shareGoodsDataMap = new ShareGoodsDaoImpl().getUserShareData(getUserId());
        ActivityInfo activityInfo = ShareActivityMgr.getQyfxActivityInfo();
        if (activityInfo != null) {
            userQyfxData = ShareActivityBusiness.getUserQyfxData(player.getUserId(), activityInfo.getActivityId());
            if (userQyfxData == null) {
                initUserData(activityInfo.getActivityId());
            }
        }
        return true;
    }

    @Override
    public boolean afterLoadData() {
        // 容错
        if (userShareData != null && StringUtils.isNullOrEmpty(userShareData.getShareCode())) {
            String shareCode = ShareMgr.getShareCode(getUserId());
            userShareData.setShareCode(shareCode);
        }
        return true;
    }

    @Override
    public boolean saveData() {
        if (userShareData != null) {
            if (userShareData.isInsertOption()) {
                new ShareDataDaoImpl().add(userShareData);
            } else if (userShareData.isUpdateOption()) {
                new ShareDataDaoImpl().update(userShareData);
            }
        }
        if (shareGoodsDataMap != null) {
            for (UserShareGoodsData data : new ArrayList<>(shareGoodsDataMap.values())) {
                if (data.isInsertOption()) {
                    new ShareGoodsDaoImpl().add(data);
                }
            }
        }
        if (userQyfxData != null) {
            if (userQyfxData.isInsertOption()) {
                ShareActivityBusiness.addUserQyfxData(userQyfxData);
            } else if (userQyfxData.isUpdateOption()) {
                ShareActivityBusiness.updateUserQyfxData(userQyfxData);
            }
        }
        return true;
    }


    public void systemOpen() {
        if (userShareData == null) {
            initUserShareData();
        }
        syncShareDataMsg();
    }

    public void syncData() {
        checkInvitedCode();
        if (userShareData.getInvitedServerId() != 0) {
            ShareProto.SyncUserDataToInviterMsg.Builder syncMsg = ShareProto.SyncUserDataToInviterMsg.newBuilder();
            syncMsg.setInviterServerId(userShareData.getInvitedServerId());
            syncMsg.setInviterUserId(userShareData.getInvitedUserId());

            ShareProto.InvitationDataMsg.Builder msg = ShareProto.InvitationDataMsg.newBuilder();
            msg.setUserId(player.getUserInfo().getUserAliasId());
            msg.setServerId(GameServer.getInstance().getServerId());
            msg.setNickName(player.getUserInfo().getNickName());
            msg.setEarnSpeed(player.getUserInfo().getEarnSpeed().toString());
            msg.setVipExp(player.getUserInfo().getVipExp());
            msg.setRegisterTime(player.getUserInfo().getRegisterTime());
            msg.setOpenId(player.getUserInfo().getOpenId());
            syncMsg.setData(msg);

            player.sendPacket(CrossProtocol.C_CROSS_SHARE_SYNC, syncMsg);
        }
    }

    public int getSaveDeskReward() {
        long rewardState = player.getModule(AttributeModule.class).getAttribute(ePlayerAttrType.SaveDeskReward);
        if (rewardState == 1) {
            return GameErrorCode.E_ACTIVITY_REWARD_IS_GET;
        }
        String reward = ShareActivityMgr.getSaveDeskReward();
        if (reward.isEmpty()) {
            return GameErrorCode.E_REWARD_CONFIG_NO_FOUND;
        }
        //领奖 设置领奖状态
        player.getModule(AttributeModule.class).setAttribute(ePlayerAttrType.SaveDeskReward, 1);
        player.getModule(CurrencyModule.class).addCurrency(PropertyHelper.parseStringToProperty(reward), eLogMoneyType.Share, eLogMoneyType.SaveDeskReward);
        ShareProto.SaveDeskRewardRespMsg.Builder respMsg = ShareProto.SaveDeskRewardRespMsg.newBuilder();
        respMsg.setRet(0);
        respMsg.setReward(reward);
        player.sendPacket(ClientProtocol.U_SHARE_SAVE_DESK_REWARD, respMsg);
        return 0;
    }

    public int getSCYLReward() {
        long rewardState = player.getModule(AttributeModule.class).getAttribute(ePlayerAttrType.ScylReward);
        if (rewardState == 1) {
            return GameErrorCode.E_ACTIVITY_REWARD_IS_GET;
        }
        String reward = ShareActivityMgr.getScylReward();
        if (reward.isEmpty()) {
            return GameErrorCode.E_REWARD_CONFIG_NO_FOUND;
        }
        //领奖 设置领奖状态
        player.getModule(AttributeModule.class).setAttribute(ePlayerAttrType.ScylReward, 1);
        player.getModule(CurrencyModule.class).addCurrency(PropertyHelper.parseStringToProperty(reward), eLogMoneyType.Share, eLogMoneyType.ScylReward);
        ShareProto.SaveDeskRewardRespMsg.Builder respMsg = ShareProto.SaveDeskRewardRespMsg.newBuilder();
        respMsg.setRet(0);
        respMsg.setReward(reward);
        player.sendPacket(ClientProtocol.U_SCYL_REWARD, respMsg);
        return 0;
    }

    public int getDyBackReward() {
        long rewardState = player.getModule(AttributeModule.class).getAttribute(ePlayerAttrType.DyBackReward);
        if (rewardState == 2) {
            return GameErrorCode.E_ACTIVITY_REWARD_IS_GET;
        }
        String reward = ShareActivityMgr.getDyBackReward();
        if (reward.isEmpty()) {
            return GameErrorCode.E_REWARD_CONFIG_NO_FOUND;
        }
        //领奖 设置领奖状态
        player.getModule(AttributeModule.class).setAttribute(ePlayerAttrType.DyBackReward, 2);
        player.getModule(CurrencyModule.class).addCurrency(PropertyHelper.parseStringToProperty(reward), eLogMoneyType.Share, eLogMoneyType.DyBackReward);
        ShareProto.SaveDeskRewardRespMsg.Builder respMsg = ShareProto.SaveDeskRewardRespMsg.newBuilder();
        respMsg.setRet(0);
        respMsg.setReward(reward);
        player.sendPacket(ClientProtocol.U_DY_BACK_REWARD, respMsg);
        return 0;
    }


    public void dailyReset() {
        try {
            if (userShareData != null) {
                long lastResetTime = userShareData.getLastResetTime();
                if (!DateHelper.isSameDay(lastResetTime / 1000, System.currentTimeMillis() / 1000)) {
                    userShareData.setLastResetTime(System.currentTimeMillis());
                    userShareData.setNextShareTime(System.currentTimeMillis());
                    userShareData.setNextInvitationTime(System.currentTimeMillis());
                    userShareData.setTodayShareTimes(0);
                }
            }
            if (userQyfxData != null) {
                long dayResetTime = userQyfxData.getDayResetTime();
                if (!DateHelper.isSameDay(dayResetTime / 1000, System.currentTimeMillis() / 1000)) {
                    userQyfxData.setDayResetTime(System.currentTimeMillis());
                    userQyfxData.setSharePerson(0);
                }
            }
        } catch (Exception e) {
            log.error("{} reset error.", getUserId(), e);
        }
    }

    public int shareGoods(int id) {
        //是否领取过
        if (shareGoodsDataMap.containsKey(id)) {
            return GameErrorCode.E_SHARE_GOODS_ALREADY;
        }
        Property reward;
        //判断奖励
        if (GoodsMgr.isPatronsGoods(id)) {
            UserPatrons userPatrons = player.getModule(PatronsModule.class).getUserPatrons(id);
            if (userPatrons == null) {
                return GameErrorCode.E_SHARE_GOODS_NOT_HAVE_GOODS;
            }
            reward = PropertyHelper.parseStringToProperty(GameConfig.SHARE_GIFT_NEW_PATRONS_REWARDS_CONFIG);
        } else if (GoodsMgr.isBeautyGoods(id)) {
            UserBeauty userBeauty = player.getModule(BeautyModule.class).getUserBeauty(id);
            if (userBeauty == null) {
                return GameErrorCode.E_SHARE_GOODS_NOT_HAVE_GOODS;
            }
            reward = PropertyHelper.parseStringToProperty(GameConfig.SHARE_GIFT_NEW_BEAUTY_REWARDS_CONFIG);
        }else {
            return GameErrorCode.E_SHARE_GOODS_WRONG_ID;
        }
        //发奖
        UserShareGoodsData data = new UserShareGoodsData();
        data.setUserId(getUserId());
        data.setGoodsId(id);
        data.setRewardTime(System.currentTimeMillis());
        data.setInsertOption();
        shareGoodsDataMap.put(id, data);
        player.getModule(CurrencyModule.class).addCurrency(reward, eLogMoneyType.Activity, eLogMoneyType.ShareNewGoods);

        return 0;
    }

    public int qyfxInviteSuccess(int activityId) {
        if (ShareActivityMgr.getQyfxActivityInfo().getActivityId() != activityId) {
            return GameErrorCode.E_ACTIVITY_NO_FOUND;
        }
        if (userQyfxData.getActivityId() != activityId) {
            return GameErrorCode.E_ACTIVITY_NO_FOUND;
        }
        if (userQyfxData.getSharePerson() >= ShareActivityMgr.getQyfxShareMaxPerson()) {
            return GameErrorCode.E_QYFX_INVITE_TIMES_LIMIT;
        }
        userQyfxData.setSharePerson(userQyfxData.getSharePerson() + 1);
        player.notifyListener(eGamePlayerEventType.QyfxInviteNewPlayer.getValue(), 1);
        syncUserData();
        return 0;
    }

    public void initUserData(int activityId){
        if (userQyfxData == null || userQyfxData.getActivityId() != activityId) {
            UserQyfxData tempUserData = new UserQyfxData();
            tempUserData.setActivityId(activityId);
            tempUserData.setUserId(getUserId());
            tempUserData.setSharePerson(0);
            tempUserData.setDayResetTime(System.currentTimeMillis());
            tempUserData.setInsertOption();
            userQyfxData = tempUserData;
        }
    }

    public void syncUserData(){
        ShareProto.DearShareDataMsg.Builder syncMsg = ShareProto.DearShareDataMsg.newBuilder();
        int leftTimes = Math.max(ShareActivityMgr.getQyfxShareMaxPerson() - userQyfxData.getSharePerson(), 0);
        syncMsg.setTodayDearShareLeftTimes(leftTimes);
        player.sendPacket(ClientProtocol.U_ACTIVITY_DEAR_SHARE_DATA, syncMsg);
    }
}
